package cuppics;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

public class Prj32 {

	/**
	 * We shall say that an n-digit number is pandigital if it makes use of all
	 * the digits 1 to n exactly once; for example, the 5-digit number, 15234,
	 * is 1 through 5 pandigital.
	 * 
	 * The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
	 * multiplicand, multiplier, and product is 1 through 9 pandigital.
	 * 
	 * Find the sum of all products whose multiplicand/multiplier/product
	 * identity can be written as a 1 through 9 pandigital.
	 * 
	 * HINT: Some products can be obtained in more than one way so be sure to
	 * only include it once in your sum.
	 */
	@Test
	public void test() {
		// System.out.println(9 * 9999);
		// System.out.println(10 * 999);
		// System.out.println(99 * 999);
		System.out.println(Calculator.calculate());
	}

	public static class Calculator {

		/**
		 * a + b + c = 9; a = 1 && b = 4; a = 2 && b = 3;
		 * 
		 * @return
		 */
		public static int calculate() {

			int a = 0;
			int b = 0;
			Set<Integer> set = new HashSet<Integer>();
			for (a = 1; a <= 10; a++) {
				for (b = 1000; b <= 10000; b++) {
					if (checkNum(a, b, a * b)) {
						System.out.println(a + "*" + b + "=" + a * b);
						set.add(a * b);
					}
				}
			}

			for (a = 10; a <= 100; a++) {
				for (b = 100; b <= 1000; b++) {
					if (checkNum(a, b, a * b)) {
						System.out.println(a + "*" + b + "=" + a * b);
						set.add(a * b);
					}
				}
			}

			int sum = 0;
			for (Integer intVal : set) {
				sum += intVal;

			}

			return sum;
		}

		public static boolean checkNum(int a, int b, int c) {
			Set<Integer> set = new HashSet<Integer>();
			int val = a;
			while (val >= 10) {
				if (set.contains(val % 10)) {
					return false;
				}
				set.add(val % 10);
				val /= 10;
			}
			if (set.contains(val)) {
				return false;
			}
			set.add(val);
			val = b;
			while (val >= 10) {
				if (set.contains(val % 10)) {
					return false;
				}
				set.add(val % 10);
				val /= 10;
			}
			if (set.contains(val)) {
				return false;
			}
			set.add(val);
			val = c;
			while (val >= 10) {
				if (set.contains(val % 10)) {
					return false;
				}
				set.add(val % 10);
				val /= 10;
			}
			if (set.contains(val)) {
				return false;
			}
			set.add(val);
			return set.size() == 9 && set.contains(1) && set.contains(2)
					&& set.contains(3) && set.contains(4) && set.contains(5)
					&& set.contains(6) && set.contains(7) && set.contains(8)
					&& set.contains(9);
		}

	}
}
